<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 页面头部 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div
        class="container mx-auto px-4 py-4 flex justify-between items-center"
      >
        <h1 class="text-2xl font-bold text-primary flex items-center">
          <el-icon class="mr-2"><Shop /></el-icon>
          美食店铺精选
        </h1>
        <h1 class="flex items-center centerText">
          大锤精选(剩余26天) 倪选（剩余3天）
        </h1>
        <h1
          @click="openImg"
          v-loading:="isLoading"
          class="flex items-center centerText"
        >
          点我支持
        </h1>
      </div>
    </header>
    <div class="img">
      <img
        @click="router.push('/log-lottery/home')"
        src="@/assets/images/页面图片组合 (1)_副本.png"
        alt=""
      />
    </div>
    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-8">
      <!-- 筛选条件（改为form布局） -->
      <div class="mb-6 bg-white p-4 rounded-lg shadow-sm">
        <!-- 使用el-form的inline模式实现一行布局 -->
        <el-form inline :model="filterForm" class="w-full selectForm">
          <!-- 菜系筛选 -->
          <el-form-item>
            <el-select
              v-model="selectedCuisine"
              placeholder="菜系"
              clearable
              class="w-36"
            >
              <el-option label="全部菜系" value="" />
              <el-option label="中餐" value="中餐" />
              <el-option label="西餐" value="西餐" />
              <el-option label="日料" value="日料" />
              <el-option label="韩餐" value="韩餐" />
              <el-option label="快餐" value="快餐" />
            </el-select>
          </el-form-item>

          <!-- 价格筛选 -->
          <el-form-item>
            <el-select
              v-model="selectedPrice"
              placeholder="价格"
              clearable
              class="w-36"
            >
              <el-option label="全部价格" value="" />
              <el-option label="¥ 经济实惠" value="经济实惠" />
              <el-option label="¥¥ 中等价位" value="中等价位" />
              <el-option label="¥¥¥ 高端消费" value="高端消费" />
            </el-select>
          </el-form-item>

          <!-- 评分筛选 -->
          <el-form-item>
            <el-select
              v-model="selectedRating"
              placeholder="评分"
              clearable
              class="w-36"
            >
              <el-option label="全部评分" value="" />
              <el-option label="4分以上" value="4" />
              <el-option label="3.5分以上" value="3.5" />
              <el-option label="3分以上" value="3" />
            </el-select>
          </el-form-item>
          <!-- 评分筛选 -->
          <el-form-item style="float: right">
            <el-input
              style="width: 300px"
              v-model="searchQuery"
              placeholder="搜索店铺或菜品..."
              prefix-icon="Search"
              class="w-64"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 店铺列表（保持不变） -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="restaurant in filteredRestaurants"
          :key="restaurant.id"
          class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow cursor-pointer"
          @click="showRestaurantDetail(restaurant)"
        >
          <div class="relative h-48">
            <img
              :src="restaurant.coverImage"
              :alt="restaurant.name"
              class="w-full h-full object-cover"
            />
            <div
              class="absolute top-3 left-3 bg-primary text-white text-sm px-2 py-1 rounded"
            >
              {{ restaurant.cuisine }}
            </div>
            <div
              class="absolute top-3 right-3 bg-white/90 text-primary text-sm px-2 py-1 rounded flex items-center"
            >
              <el-icon size="16" class="mr-1"><Star /></el-icon>
              {{ restaurant.rating }}
            </div>
          </div>

          <div class="p-4">
            <div class="flex justify-between items-start mb-2">
              <h3 class="font-bold text-lg">{{ restaurant.name }}</h3>
              <span class="text-gray-500">{{ restaurant.priceRange }}</span>
            </div>

            <div class="flex items-center text-gray-500 text-sm mb-3">
              <el-icon size="16" class="mr-1"><MapLocation /></el-icon>
              {{ restaurant.distance }} 公里
              <span class="mx-2">|</span>
              <el-icon size="16" class="mr-1"><Clock /></el-icon>
              {{ restaurant.deliveryTime }} 分钟
            </div>

            <div class="flex flex-wrap gap-2">
              <span
                class="bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded"
                v-for="tag in restaurant.tags"
                :key="tag"
              >
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 店铺详情弹窗（保持不变） -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentRestaurant?.name || ''"
      :width="isMobile ? '90%' : '800px'"
      :before-close="handleClose"
    >
      <div v-if="currentRestaurant">
        <!-- 店铺基本信息 -->
        <div class="mb-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div>
              <h3 class="text-xl font-bold mb-2">
                {{ currentRestaurant.name }}
              </h3>
              <div class="flex items-center text-gray-600 mb-2">
                <el-rate
                  :value="currentRestaurant.rating"
                  disabled
                  :max="5"
                  :precision="0.5"
                  class="mr-2"
                />
                <span>({{ currentRestaurant.reviewCount }} 条评价)</span>
              </div>

              <div class="space-y-2 text-sm">
                <p>
                  <span class="text-gray-500">菜系：</span
                  >{{ currentRestaurant.cuisine }}
                </p>
                <p>
                  <span class="text-gray-500">价格：</span
                  >{{ currentRestaurant.priceRange }}
                </p>
                <p>
                  <span class="text-gray-500">电话：</span
                  >{{ currentRestaurant.phone }}
                </p>
                <p>
                  <span class="text-gray-500">地址：</span
                  >{{ currentRestaurant.address }}
                </p>
              </div>
            </div>

            <div>
              <el-carousel height="200px">
                <el-carousel-item
                  v-for="(img, index) in currentRestaurant.images"
                  :key="index"
                >
                  <img
                    :src="img"
                    :alt="`${currentRestaurant.name}环境图${index + 1}`"
                    class="w-full h-full object-cover"
                  />
                </el-carousel-item>
              </el-carousel>
            </div>
          </div>

          <div>
            <h4 class="font-bold mb-2">店铺介绍</h4>
            <p class="text-gray-600 text-sm">
              {{ currentRestaurant.description }}
            </p>
          </div>
        </div>

        <!-- 推荐菜品 -->
        <div>
          <h4 class="font-bold mb-3">推荐菜品</h4>
          <el-table
            :data="currentRestaurant.dishes"
            border
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="name" label="菜品名称" width="200" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="price" label="价格" width="100" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="addToOrder(scope.row)"
                >
                  <el-icon size="16" class="mr-1"><ShoppingCart /></el-icon>
                  加入订单
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-between items-center w-full">
          <div>
            <span class="text-gray-500">已选 {{ orderCount }} 件商品</span>
            <span class="ml-4 text-primary font-bold"
              >合计：¥{{ totalPrice.toFixed(2) }}</span
            >
          </div>
          <el-button
            type="primary"
            @click="submitOrder"
            :disabled="orderCount === 0"
          >
            提交订单
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <el-dialog v-model="fuImgShow" title="感谢支持" width="500" center>
    <el-image
      v-if="fuSrc"
      :src="fuSrc"
      fit="cover"
      class="w-full h-full"
      @click="fuImgShow = false"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import fuSrc from "@/assets/images/fu.png";
import data from "./fineFood";
import { useRouter } from "vue-router";
const isLoading = ref(false);
// 响应式判断
const isMobile = ref(false);
const router = useRouter();

// 筛选条件（新增form绑定对象，用于el-form）
const filterForm = ref({});
const searchQuery = ref("");
const selectedCuisine = ref("");
const selectedPrice = ref("");
const selectedRating = ref("");
const fuImgShow = ref(false);
const openImg = () => {
  fuImgShow.value = true;
};
// 店铺数据（保持不变）
const restaurants = ref(data);

// 弹窗状态（保持不变）
const dialogVisible = ref(false);
const currentRestaurant = ref(null);

// 订单相关（保持不变）
const orderItems = ref([]);
const orderCount = computed(() =>
  orderItems.value.reduce((total, item) => total + item.quantity, 0)
);
const totalPrice = computed(() =>
  orderItems.value.reduce(
    (total, item) => total + item.price * item.quantity,
    0
  )
);
const showSuccessNotify = ref(false);

// 筛选后的店铺列表（保持不变）
const filteredRestaurants = computed(() => {
  return restaurants.value.filter((restaurant) => {
    // 搜索筛选
    const matchesSearch =
      searchQuery.value === "" ||
      restaurant.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      restaurant.cuisine
        .toLowerCase()
        .includes(searchQuery.value.toLowerCase()) ||
      restaurant.tags.some((tag) =>
        tag.toLowerCase().includes(searchQuery.value.toLowerCase())
      ) ||
      restaurant.dishes.some((dish) =>
        dish.name.toLowerCase().includes(searchQuery.value.toLowerCase())
      );

    // 菜系筛选
    const matchesCuisine =
      selectedCuisine.value === "" ||
      restaurant.cuisine === selectedCuisine.value;

    // 价格筛选
    const matchesPrice =
      selectedPrice.value === "" ||
      restaurant.priceRange.includes(selectedPrice.value);

    // 评分筛选
    const matchesRating =
      selectedRating.value === "" ||
      restaurant.rating >= parseFloat(selectedRating.value);

    return matchesSearch && matchesCuisine && matchesPrice && matchesRating;
  });
});

// 方法（保持不变）
const showRestaurantDetail = (restaurant) => {
  currentRestaurant.value = { ...restaurant };
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
};

const addToOrder = (dish) => {
  const existingItem = orderItems.value.find((item) => item.id === dish.id);

  if (existingItem) {
    existingItem.quantity++;
  } else {
    orderItems.value.push({ ...dish, quantity: 1 });
  }
};

const submitOrder = () => {
  if (orderCount.value > 0) {
    showSuccessNotify.value = true;
    orderItems.value = [];
    dialogVisible.value = false;
  }
};

// 监听窗口大小变化（保持不变）
onMounted(() => {
  checkScreenSize();
  window.addEventListener("resize", checkScreenSize);
});

const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};
</script>

<style scoped lang="scss">
.centerText {
  cursor: pointer;
  background: linear-gradient(45deg, #d32f2f, #ff6b6b);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: inline-block;
}

.img {
  cursor: pointer;
  width: 300px;
  position: fixed;
  right: 40px;
  top: 300px;
  img {
    width: 100%;
  }
}
.selectForm {
  width: 100%;
  .el-form-item {
    min-width: 200px;
  }
}
/* 自定义样式 */
.el-rate {
  --el-rate-icon-size: 16px;
}

.el-carousel__item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.el-table {
  --el-table-border-color: #e5e7eb;
}

.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

/* 调整form-item间距 */
:deep(.el-form-item) {
  margin-right: 16px; /* 增加项目之间的间距 */
  margin-bottom: 0; /* 去除默认底部间距 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-dialog__body {
    max-height: 50vh;
  }

  /* 小屏幕下筛选条件自动换行 */
  :deep(.el-form-inline .el-form-item) {
    margin-bottom: 12px;
  }
}
</style>